<template>
    <div>
        <div><h1>订单列表</h1></div>
        <div>
            <el-form
                :inline="true"
                :model="searchForm"
                class="demo-form-inline"
            >
                <el-form-item label="关键字">
                    <el-input
                        v-model="searchForm.keyWord"
                        placeholder="请输入关键字"
                        clearable
                    />
                </el-form-item>
                <!-- 0待支付1已支付2待发货3已签收 -->
                <el-form-item label="订单状态">
                    <el-select
                        v-model="searchForm.statusId"
                        style="width: 140px"
                        placeholder="选择订单状态"
                        clearable
                    >
                        <el-option label="待支付" :value="0" />
                        <el-option label="已支付" :value="1" />
                        <el-option label="待发货" :value="2" />
                        <el-option label="已签收" :value="3" />
                    </el-select>
                </el-form-item>
                <!-- 0普通订单1秒杀订单2团购订单 -->
                <el-form-item label="订单类型">
                    <el-select
                        v-model="searchForm.typeId"
                        placeholder="选择订单类型"
                        style="width: 140px"
                        clearable
                    >
                        <el-option label="普通订单" :value="0" />
                        <el-option label="秒杀订单" :value="1" />
                        <el-option label="团购订单" :value="2" />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="onSearch">查询</el-button>
                    <el-button
                        type="danger"
                        @click="onDeleteAll"
                        :disabled="multipleSelection.length == 0"
                        >批量删除</el-button
                    >
                    <el-button type="success" @click="onExportAll"
                        >导出订单</el-button
                    >
                    <el-button type="success" @click="onShowAddOrder"
                        >新增订单</el-button
                    >
                </el-form-item>
            </el-form>
        </div>
        <div>
            <el-table
                :data="orderList"
                stripe
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="orderId" label="ID" width="100" />
                <el-table-column prop="orderNo" label="编号" width="180" />
                <el-table-column prop="orderType" label="类型" width="100">
                    <template #default="scope">
                        <span v-if="scope.row.orderType === 0">普通订单</span>
                        <span v-if="scope.row.orderType === 1">秒杀订单</span>
                        <span v-if="scope.row.orderType === 2">团购订单</span>
                    </template>
                </el-table-column>
                <el-table-column prop="nickName" label="买家" width="100" />
                <el-table-column prop="prodInfo" label="商品名称" width="180" />
                <el-table-column prop="amount" label="金额" width="100" />
                <el-table-column prop="orderStatus" label="状态" width="100">
                    <template #default="scope">
                        <span v-if="scope.row.orderStatus === 0">待支付</span>
                        <span v-if="scope.row.orderStatus === 1">已支付</span>
                        <span v-if="scope.row.orderStatus === 2">待发货</span>
                        <span v-if="scope.row.orderStatus === 3">已签收</span>
                    </template>
                </el-table-column>
                <el-table-column prop="prodNum" label="数量" width="100" />
                <el-table-column label="图片" width="160">
                    <template #default="scope">
                        <el-image
                            v-for="item in scope.row.imageList"
                            :src="item"
                            :key="item"
                            alt=""
                            style="width: 50px; height: 50px"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="时间" width="160" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button
                            type="primary"
                            size="small"
                            @click="onShowOrderRecord(scope.row)"
                            >查看记录</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div style="margin-top: 20px">
            <el-pagination
                v-model:current-page="searchForm.pageNum"
                v-model:page-size="searchForm.pageSize"
                :page-sizes="[2, 4, 6, 8]"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
        <div>
            <el-dialog v-model="dialogFormVisible" title="添加订单" width="800">
                <el-form ref="ruleFormRef" :model="form" :rules="rules">
                    <el-form-item
                        label="选择商品"
                        prop="prodId"
                        :label-width="formLabelWidth"
                    >
                        <el-select
                            v-model="form.prodId"
                            placeholder="请选择商品"
                            @change="onChangeProd"
                        >
                            <el-option
                                v-for="item in prodList"
                                :label="item.prodName"
                                :value="item.prodId"
                                :key="item.prodId"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="商品信息"
                        :label-width="formLabelWidth"
                    >
                        <el-table
                            :data="prodInfoList"
                            stripe
                            style="width: 100%"
                            @selection-change="onSelectionChange"
                        >
                            <el-table-column type="selection" width="55" />
                            <el-table-column
                                prop="infoId"
                                label="ID"
                                width="100"
                            />
                            <el-table-column
                                prop="prodName"
                                label="名称"
                                width="160"
                            />
                            <el-table-column
                                prop="prodPrice"
                                label="价格"
                                width="120"
                            />
                            <el-table-column
                                prop="buyNum"
                                label="购买数量"
                                width="120"
                            />
                            <el-table-column label="操作" />
                        </el-table>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogFormVisible = false"
                            >放弃</el-button
                        >
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            确认
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
        <div>
            <el-drawer
                v-model="drawerShow"
                title="订单记录"
                direction="rtl"
                size="50%"
            >
                <el-table :data="recordData">
                    <el-table-column property="recordId" label="序号" width="150" />
                    <el-table-column property="recordContent" label="操作记录" width="200" />
                    <el-table-column property="createTime" label="操作时间" />
                </el-table>
            </el-drawer>
        </div>
    </div>
</template>

<script setup lang="ts">
import {
    getOrderList,
    deleteAll,
    getProdList,
    getProdInfoList,
    addOrder,
    getOrderRecordList,
} from "@/api/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, ref, reactive } from "vue";
import type { FormInstance, FormRules } from 'element-plus'

interface RuleForm {
  prodId: number
}

const orderList = ref([]);
const total = ref(0);
const searchForm = ref({
    pageNum: 1,
    pageSize: 2,
    keyWord: null,
    statusId: null,
    typeId: null,
});

const multipleSelection = ref<any[]>([]);
const selectProdList = ref<any[]>([]);


const recordData = ref([]);
const drawerShow = ref(false);

const ruleFormRef = ref<FormInstance>()

const rules = reactive<FormRules<RuleForm>>({
  prodId: [
    { required: true, message: '请选择商品', trigger: 'blur' },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 表单校验通过
      onSubmitAdddOrder();
    } else {
      // 表单校验失败
    }
  })
}

// 查看订单记录
const onShowOrderRecord = (row: any) => {
    console.log("onShowOrderRecord", row);
    getOrderRecordList(row.orderId).then((res) => {
        if(res.data.code == 200) {
            recordData.value = res.data.data;
            drawerShow.value = true;
        }
        else {
            ElMessage.error(res.data.msg);
        }
    });
    
};

// 添加订单
const onSubmitAdddOrder = () => {
    console.log("onSubmitAdddOrder", selectProdList.value);

    // 校验参数
    if (selectProdList.value.length == 0) {
        ElMessage.error("请选择商品");
        return;
    }

    // 添加订单
    addOrder(selectProdList.value).then((res) => {
        if (res.data.code == 200) {
            ElMessage.success("添加成功");
            dialogFormVisible.value = false;
            loadOrderList();
        } else {
            ElMessage.error(res.data.msg);
        }
    });
};

// 批量选择订单时间
const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val;
    console.log("handleSelectionChange", multipleSelection.value);
};

// 批量选择商品事件
const onSelectionChange = (val: any[]) => {
    selectProdList.value = val;
    console.log("onSelectionChange", selectProdList.value);
};

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = ref({
    prodId: null,
});
const prodList = ref([]);
const prodInfoList = ref([]);

const onChangeProd = (value: any) => {
    console.log("onChangeProd", value);
    getProdInfoList({ pageNum: 1, pageSize: 1000, typeId: value }).then(
        (res) => {
            if (res.data.code == 200) {
                prodInfoList.value = res.data.data.records;

                // 默认购买数量为1
                if (prodInfoList.value.length > 0) {
                    prodInfoList.value.forEach((item) => {
                        item.buyNum = 1;
                    });
                }
            }
        }
    );
};

// 新增订单
const onShowAddOrder = () => {
    console.log("新增订单");
    // 显示 新增订单对话框
    dialogFormVisible.value = true;
};

// 批量导出
const onExportAll = () => {
    console.log(" 批量导出", orderList.value);
    // 拼接IDS字符串
    let ids = "";
    orderList.value.forEach((item) => {
        if (ids == "") {
            ids = item.orderId;
        } else {
            ids = ids + "," + item.orderId;
        }
    });

    // 拼接请求url
    let url = "http://localhost:9011/shop/order/exportExcel/" + ids;
    window.open(url);
};

// 批量删除
const onDeleteAll = () => {
    console.log(" 批量删除", multipleSelection.value);

    ElMessageBox.confirm("删除订单后数据无法恢复,您确认要删除吗?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "放弃",
        type: "warning",
    })
        .then(() => {
            // 点击确认
            // 批量删除订单
            deleteAll(multipleSelection.value).then((res) => {
                if (res.data.code == 200) {
                    ElMessage.success("删除成功");
                    loadOrderList();
                } else {
                    ElMessage.error(res.data.msg);
                }
            });
        })
        .catch(() => {
            // 放弃
        });
};

const onSearch = () => {
    console.log("搜索", searchForm.value);
    loadOrderList();
};

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
    searchForm.value.pageSize = val;
    loadOrderList();
};
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
    searchForm.value.pageNum = val;
    loadOrderList();
};

// 加载订单分页列表
const loadOrderList = () => {
    getOrderList(searchForm.value).then((res: any) => {
        if (res.data.code == 200) {
            orderList.value = res.data.data.records;
            total.value = res.data.data.total;
        }
    });
};

// 页面加载钩子函数
onMounted(() => {
    loadOrderList();

    // 加载所有的商品列表
    getProdList({ pageNum: 1, pageSize: 1000 }).then((res: any) => {
        if (res.data.code == 200) {
            prodList.value = res.data.data.records;
        }
    });
});
</script>

<style scoped></style>
